<template>
  <div class="dictData">
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form
          ref="form"
          :model="form"
          label-width="80px"
          :inline="true"
          class="dialog-search-form"
        >
          <el-form-item label="字典标签">
            <el-input v-model="form.dictLabel" style="width: 250px" clearable />
          </el-form-item>
          <el-form-item label="数据状态">
            <el-select
              v-model="form.statusData"
              placeholder="请选择"
              style="width: 250px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn-search"
              round
              icon="el-icon-search"
              size="medium"
              @click="initTable"
              >搜索</el-button
            >
            <el-button
              class="btn-search"
              round
              icon="el-icon-refresh"
              size="medium"
              @click="resetTable"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition>
    <card-table>
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:dict:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:dict:edit')"
            class="btn-search"
            size="small"
            icon="el-icon-edit"
            :disabled="btnDisabledSingle"
            @click="handleClick(null, 'edit')"
            >编辑</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:dict:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-delete"
            :disabled="btnDisabled"
            @click="handleClick(null, 'delete')"
            >删除</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:dict:export')"
            class="btn-search"
            size="small"
            icon="el-icon-upload2"
            @click="handleClick(null, 'export')"
            >导出</el-button
          >
          <span
            v-if="isSuperAdmin || hasPermission('system:dict:list')"
            style="padding: 0 10px 0 30px"
            >字典名称</span
          >
          <el-select
            v-if="isSuperAdmin || hasPermission('system:dict:list')"
            v-model="form.dictName"
            placeholder="请选择"
            style="width: 250px"
            @change="onChangeDictName()"
          >
            <el-option
              v-for="item in optionsDictname"
              :key="item.dictId"
              :label="item.dictName"
              :value="item.dictName"
            />
          </el-select>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :search-show="(true && hasPermission('system:dict:list')) || isSuperAdmin"
            :table-header="tableHeader"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        border
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
        max-height="500"
        @selection-change="handleSelectionChange"
        size="small"
        highlight-selection-row
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          sortable
          align="center"
        >
          <template #default="scope">
            <span v-if="item.prop === 'status'">{{
              scope.row[item.prop] == "0" ? "正常" : "停用"
            }}</span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>
    <DialogDictionary
      v-model="dialogVisible"
      :field="field"
      :dialogType="dialogType"
      :dictType="form.dictType"
      :rowData="rowDataItem"
      @init="initTable"
      @close="
        () => {
          dialogVisible = false;
        }
      "
    />
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import DialogDictionary from "./DialogDictionary.vue";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import {
  dictItemList,
  dictTypeList,
  dictItemRemove,
  dictItemExport,
} from "@/api/systemmanagement";
export default {
  name: "BusinessList",
  components: {
    CardSearch,
    CardTable,
    TableAction,
    DialogDictionary,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      dialogVisible: false,

      field: "",
      dialogType: "",
      form: {
        statusData: "2",
        dictLabel: "",
      },
      dictName: "",
      dictType: "",
      input: "",
      optionsDictname: [],
      options: [
        {
          value: "2",
          label: "所有",
        },
        {
          value: "0",
          label: "正常",
        },
        {
          value: "1",
          label: "停用",
        },
      ],
      value: "0",
      tableHeader: [
        {
          title: "字典编码",
          prop: "dictCode",
          width: "100",
          visible: true,
        },
        {
          title: "字典标签",
          prop: "dictLabel",
          width: "120",
          visible: true,
        },
        {
          title: "字典键值",
          prop: "dictValue",
          width: "120",
          visible: true,
        },
        {
          title: "字典排序",
          prop: "dictSort",
          width: "120",
          visible: true,
        },
        {
          title: "字典状态",
          prop: "status",
          width: "120",
          visible: true,
        },
        {
          title: "备注",
          prop: "remark",
          width: "120",
          visible: true,
        },
        {
          title: "创建时间",
          prop: "createTime",
          width: "200",
          visible: true,
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      btnDisabledSingle: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      rowDataItem: {},
    };
  },
  props: {
    rowData: {
      type: Object,
      default: {},
    },
  },
  watch: {
    rowData: {
      handler(val) {
        // 根据实际传递的数据结构调整
        if (val) {
          if (typeof val === "object" && val.dictType) {
            this.dictType = val.dictType;
            this.form = { ...val, dictLabel: "", statusData: "2" };
          }
          // 如果需要在 rowData 变化时重新加载表格数据，取消下面的注释
          this.initTable();
        }
      },
      deep: true,
      immediate: true, // 确保组件初始化时也能处理传入的数据
    },
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.initDictType();
  },
  methods: {
    initTable() {
      let statusData = this.form.statusData == "2" ? "" : this.form.statusData;
      let data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        dictType: this.form.dictType,
        dictLabel: this.form.dictLabel,
        status: statusData,
      };
      dictItemList(data).then((res) => {
        if (res.code == 0) {
          this.tableData = res.rows;
          this.total = res.total;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    initDictType() {
      dictTypeList().then((res) => {
        if (res.code == 0) {
          this.optionsDictname = res.data;
        }
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
      if (this.multipleSelection.length == 1) {
        this.btnDisabledSingle = false;
      } else {
        this.btnDisabledSingle = true;
      }
    },
    handleClick(row, field) {
      switch (field) {
        case "add":
          this.field = "添加数据";
          this.dialogVisible = true;
          this.dialogType = "add";
          this.rowDataItem = {
            dictType: this.form.dictType,
          };
          break;
        case "edit":
          this.field = "修改数据";
          this.dialogVisible = true;
          this.dialogType = "edit";
          this.rowDataItem = this.multipleSelection[0];
          break;
        case "delete":
          this.$confirm(
            `确认删除当前选中的${this.multipleSelection.length}个字典数据吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let ids = this.multipleSelection.map((item) => item.dictCode);
            dictItemRemove({ ids: ids }).then((res) => {
              if (res.code == 0) {
                this.initTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          });
          break;
        case "export":
          let statusData = this.form.statusData == "2" ? "" : this.form.statusData;
          let data = {
            dictType: this.form.dictType,
            dictLabel: this.form.dictLabel,
            status: statusData,
          };
          dictItemExport(data).then((res) => {
            if (res.code == 0) {
              window.open(res.data.downLoadUrl, "_self");
            } else {
              this.$message.error(res.msg);
            }
          });
          break;
        default:
          break;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    resetTable() {
      this.form.dictLabel = "";
      this.form.statusData = "2";
      this.initTable();
    },
    onChangeDictName() {
      let dictType = this.optionsDictname.find(
        (item) => item.dictName === this.form.dictName
      )?.dictType;
      this.form.dictType = dictType;
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
  },
};
</script>
<style lang="scss">
.el-dialog.dialog-search-form .el-dialog__body {
  .dictData {
    .dialog-search-form {
      .el-form-item {
        .el-input {
          border: 1px solid #dcdfe6;
          width: 100%;
        }
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
  }
}
</style>
